/**
 * jims
 */
package com.jims.master.modules.drug.service;

import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.NumberUtils;
import com.jims.master.modules.doctor.dao.ApplyDrugWithdraDao;
import com.jims.master.modules.doctor.entity.ApplyDrugWithdra;
import com.jims.master.modules.drug.dao.*;
import com.jims.master.modules.drug.entity.*;
import com.jims.master.modules.finance.dao.InpBillDetailDao;
import com.jims.master.modules.finance.entity.InpBillDetail;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 药品库存管理Service
 * @author zhuq
 * @version 2017-03-10
 */
@Service
@Transactional(readOnly = true)
public class DrugStockService extends CrudService<DrugStockDao, DrugStock> {
    @Autowired
    private DrugClassDictDao drugClassDictDao;
    @Autowired
    private DrugImportMasterService drugImportMasterService;
    @Autowired
    private DrugImportDetailService drugImportDetailService;
    @Autowired
    private DrugImportMasterDao drugImportMasterDao;
    @Autowired
    private DrugImportDetailDao drugImportDetailDao;
    @Autowired
    private DrugStockDao drugStockDao;
    @Autowired
    private DrugInfoDao drugInfoDao;
    @Autowired
    private InpBillDetailDao inpBillDetailDao;
    @Autowired
    private DrugPriceDao drugPriceDao;
    @Autowired
    private ApplyDrugWithdraDao applyDrugWithdraDao;


    /* @Autowired
     private DrugStockService stockService;*/
    @Autowired
    private DrugExportMasterDao exportMasterDao;

    @Autowired
    private DrugStorageDeptDao drugStorageDeptDao;
    @Autowired
    private DrugExportMasterDao drugExportMasterDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private DrugExportDetailDao drugExportDetailDao;

    public DrugStock get(String id) {
        return super.get(id);
    }

    public List<DrugStock> findList(DrugStock drugStock) {
        return super.findList(drugStock);
    }

    public Page<DrugStock> findPage(Page<DrugStock> page, DrugStock drugStock) {
        return super.findPage(page, drugStock);
    }

    /**
     * 药品销售记录查询
     *
     * @return
     * @author ZYG
     */
    public Page<DrugStock> findAccountPage(Page<DrugStock> page, DrugStock drugStock) {
        drugStock.updateOrgId();
        drugStock.setPage(page);
        page.setList(drugStockDao.findAccountPage(drugStock));
        return page;
    }

    /**
     * 药品销售记录查询（退药）
     *
     * @return
     * @author ZYG
     */
    public Page<DrugStock> findAccountPageBack(Page<DrugStock> page, DrugStock drugStock) {
        drugStock.updateOrgId();
        drugStock.setPage(page);
        page.setList(drugStockDao.findAccountPageBack(drugStock));
        return page;
    }
    /*public Page<DrugStock> findAccountPage(Page<DrugStock> page, DrugStock drugStock) {
        return drugStockDao.findAccountPage(page, drugStock);
    }*/

    /**
     * 判断当前科室是否存在库房
     *
     * @param list
     * @return
     * @author ZYG
     */
    @Transactional(readOnly = false)
    public int ifStockExist(List<DrugStock> list) {
        DrugStock drugStock = list.get(0);
        drugStock.updateOrgId();//获取当前org_id
        drugStock.setStorageId(UserUtils.getUser().getOrgDept().getId());//获取当前科室id

    return drugStockDao.ifStockExist(drugStock);
    }

    /**
     * 药品对消入出库保存
     *
     * @param list
     * @return
     * @author ZYG
     */
    @Transactional(readOnly = false)
    public int saveInOutDrug(List<DrugStock> list) {
        int num = 1;
        Double allPriceIn=0.0;
        Double allPriceOut=0.0;
        if (null != list && list.size() > 0) {

            for (DrugStock stock : list) {
                DrugInfo drugInfo = drugInfoDao.get(stock.getInfoId());
                allPriceIn = allPriceIn + stock.getPurchasePrice() * stock.getQuantityIn();
                allPriceOut= allPriceOut + stock.getRetailPrice() * stock.getQuantityIn();

                if (drugInfo.getPackageSpec().equals(stock.getPackageSpec())) {
                    stock.setQuantityIn(stock.getQuantityIn() * drugInfo.getPackageNum());
                    stock.setQuantityOut(stock.getQuantityOut() * drugInfo.getPackageNum());
                    stock.setPackageUnits(drugInfo.getPackageUnit());
                }else{
                    stock.setPackageUnits(drugInfo.getMinUnits());
                }
                stock.setStorageId(UserUtils.getUser().getOrgDept().getId());
            }


            //组装drugImportMaster数据
            DrugStock drugStock = list.get(0);
            DrugImportMaster drugImportMaster = new DrugImportMaster();
            drugImportMaster = drugImportMasterService.createData(drugStock);
            //定义进货总金额
            //大包装数量*包装数*进货价
            drugImportMaster.setAccountReceivable(allPriceIn);
            drugImportMaster.setDocumentNo(drugImportMasterService.createDocumentNo(drugImportMaster));
            num = num * drugImportMasterDao.insert(drugImportMaster);//入库头表插数

            for (int i = 0; i < list.size(); i++) {
                //组装drugImportDetail数据并保存
                DrugImportDetail drugImportDetail = new DrugImportDetail();
                list.get(i).setQuantity(list.get(i).getQuantityIn());
                drugImportDetail = drugImportDetailService.createData(list.get(i), i, drugImportMaster.getId());
                drugImportDetail.setQuantity(String.valueOf(list.get(i).getQuantity()));
                drugImportDetail.setPackageUnits(list.get(i).getPackageUnits());
                drugImportDetail.setMinUnits(list.get(i).getMinUnits());
                num = num * drugImportDetailDao.insert(drugImportDetail);//入库子表循环插数

                //判断库房编号、infoid、批次号都存在不做操作，否则库存表插入一条数
                drugImportDetail.setStorageId(UserUtils.getUser().getOrgDept().getId());//获取当前科室id
                drugImportDetail.setMasterId(drugImportMaster.getId());
                drugImportDetail.setSupplierJc(drugStock.getSupplier());
                drugImportDetail.setInputCode(drugStock.getDocumentNo());
                DrugStock drugStockFind = new DrugStock();
                drugStockFind.updateOrgId();
                drugStockFind.setStorageId(list.get(i).getBatchNo());
                drugStockFind.setStorageId(list.get(i).getStorageId());
                drugStockFind.setStorageId(list.get(i).getDrugCode());
                drugStockFind.setStorageId(list.get(i).getInfoId());
                List<DrugStock> drugStockList = drugStockDao.findByBatchNo(drugStockFind);
                if (drugStockList.size() < 1) {
                    drugImportDetail.updateOrgId();
                    drugImportDetail.preInsert();
                    list.get(i).setRemarks(drugImportDetail.getId());
                    drugStockDao.stockInsertZero(drugImportDetail);
                } else {
                    list.get(i).setId(drugStockList.get(0).getId());
                }
            }
            //drugImportMaster.setAccountReceivable(allPrice);
            // num = num * drugImportMasterDao.update(drugImportMaster);

            drugStock.setAccountReceivable(allPriceOut);
            //出库主表

            //DrugExportMaster master = list.get(0).getDrugExportMaster();
            //DrugExportMaster master = list.get(0).getDrugExportMaster();
            drugStock.preInsert();
            drugStock.setStorageId(UserUtils.getUser().getOrgDept().getId());  //获取当前部门对应的id
            drugStock.setDocumentNo(this.createDocumentNo(drugStock));  //修改出库单号的生成
            //  drugStock.setStorageId(UserUtils.getUser().getOrgDept().getId());  //当前库房
            drugStock.setExportDate(new Date());    //出库日期
            List<DrugStorageDept> storageList = drugStorageDeptDao.getByName(list.get(0).getReceiver(), UserUtils.getOrgId());
            if (null != storageList && storageList.size() > 0) {
                for (DrugStorageDept storage : storageList) {
                    if (list.get(0).getReceiver().equals(storage.getStorageName())) {
                        drugStock.setReceiver(storage.getStorageCode());  //收货方
                        break;
                    }
                }
            }
            drugStock.setExportClass(list.get(0).getExportClass());  //出库类别
            drugStock.updateOrgId();
            //保存出库主表
            // num += exportMasterDao.insert(master);
            num += drugStockDao.insertMaster(drugStock);
            //对应的入库者
            //对应的入库日期
            //对应的入库主表ID
            String printMasterId = drugStock.getId();
            for (int i = 0; i < list.size(); i++) {
                DrugStock detail = new DrugStock();
                detail = list.get(i);
                detail.preInsert();
                detail.setMasterId(drugStock.getId());
                detail.setItemNo((i + 1) + "");
                detail.setInfoId(detail.getInfoId());
                detail.setDrugCode(detail.getDrugCode());
                detail.setPurchasePrice(detail.getRetailPrice());//入库价格
                detail.setRetailPrice(detail.getRetailPrice());//零售价格
                //detail.setInventory(NumberUtils.sub(detail.getQuantityIn(), detail.getQuantityOut()));
                detail.updateOrgId();
                detail.setImportMasterId(detail.getImportMasterId());
                detail.setPackageUnits(detail.getPackageUnits());
                detail.setMinUnits(detail.getMinUnits());
                detail.setQuantity(detail.getQuantityIn());
                detail.setInventory(0.0);//对消入出库不涉及库存
                detail.setMasterId(printMasterId);
                detail.setRemarks(detail.getRemarks());
                //保存出库明细表
                num += drugStockDao.insertDetail(detail);

            }
        }
        return num;
    }

    /**
     * (药品入出库对消选择药品自动补全(当前库房))
     *
     * @param drugInfo
     * @param orgId
     * @return
     * @author fengyg
     * @date 2017-03-17
     */
    public List<DrugExportDetail> autoDrugInOut(DrugInfo drugInfo, String orgId, String q, String limit) {
        List<DrugExportDetail> drugExportDetails = drugStockDao.autoDrugInOut(drugInfo, orgId, q, limit, UserUtils.getUser().getOrgDept().getId());
        return drugExportDetails;
    }

    /*
* 根据传来的drugExportMaster数据生成出库单据号
* @ZhuQ
* */
    public String createDocumentNo(DrugStock drugStock) {

        //根据库房获取入库单前缀
        drugStock.updateOrgId();
        DrugStorageDept drugStorageDept=drugStorageDeptDao.getByStorageCode(drugStock.getStorageId());
        String documentNo=drugStorageDept.getExportNoPrefix();
        //获取当前日期
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        documentNo=documentNo+ sdf.format(d);
        drugStock.setDocumentNo(documentNo);
        //序号
        int i = drugStockDao.findDocumentNo(drugStock);
        String num = String.valueOf(i);
        String str ="0000";
        str=str.substring(0, 4-num.length())+num;
        documentNo=documentNo+str;
        return documentNo;
    }
	@Transactional(readOnly = false)
	public int save(DrugStock drugStock) {
		return super.save(drugStock);
	}
	
	@Transactional(readOnly = false)
	public int delete(DrugStock drugStock) {
		return super.delete(drugStock);
	}

    public Page<DrugStock> findDrugList(Page<DrugStock> page, DrugStock drugStock,String drugName,String drugType){
        drugStock.updateOrgId();
//        drugStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
//        drugStock.setStorageId(UserUtils.getUser().getOrgDept() != null ? UserUtils.getUser().getOrgDept().getId() : "");
//        drugStock.setStorageId(drugStock.getStorageId() != null ? drugStock.getStorageId():"");
        drugStock.setPage(page);
        if(!"".equals(drugType) && drugType !=null){
            drugStock.setDrugCode(drugClassDictDao.get(drugType).getClassCode());
        }
        drugStock.setDrugName(drugName);
        page.setList(dao.findDrugList(drugStock));
        return page;
    }
    public List<DrugStock> findDrugByInfoId(DrugStock drugStock){
        List<DrugStock> list=dao.findDrugByInfoId(drugStock);
        return list;
    }
    public Page<DrugStock> findDrugListbat(Page<DrugStock> page, DrugStock drugStock){
        drugStock.updateOrgId();
       // drugStock.setStorageId(UserUtils.getUser().getOrgDept() != null ? UserUtils.getUser().getOrgDept().getId() : "");
        drugStock.setPage(page);
        if(!"".equals(drugStock.getDrugType()) && drugStock.getDrugType() !=null){
            drugStock.setDrugCode(drugClassDictDao.get(drugStock.getDrugType()).getClassCode());
        }
        page.setList(dao.findDrugListbat(drugStock));
        return page;
    }


    /*药品入库处理
     * @zhuq
     * 获取要入库的drugList,分别插入drugStock,drugImportMaster,drugImportDetail表
     * */
    @Transactional(readOnly = false)
    public String saveImportDrug(List<DrugStock> drugStockList){
        int num=1;
        String printMasterId="0";
        //组装drugImportMaster数据
        DrugStock drugStock=drugStockList.get(0);
        drugStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
        DrugImportMaster drugImportMaster=new DrugImportMaster();
        drugImportMaster=drugImportMasterService.createData(drugStock);
        printMasterId=drugImportMaster.getId();//获取打印主表ID
        //定义购买总金额
        Double allPrice=0.0;
        drugImportMaster.setAccountReceivable(allPrice);
        drugImportMaster.setDocumentNo(drugImportMasterService.createDocumentNo(drugImportMaster));
        num = num * drugImportMasterDao.insert(drugImportMaster);

        for(int i=0;i<drugStockList.size();i++){
            drugStockList.get(i).setStorageId(UserUtils.getUser().getOrgDept().getId());
            //组装drugImportDetail数据并保存
            DrugImportDetail drugImportDetail=new DrugImportDetail();
            drugImportDetail=drugImportDetailService.createData(drugStockList.get(i),i,drugImportMaster.getId());
            num = num * drugImportDetailDao.insert(drugImportDetail);

            //判断一个库存的，一个药品的批号是否存在，若存在，直接加数量
            DrugStock drugStockNew ;
            drugStockNew=drugStockList.get(i);
            drugStockNew.setDocumentNo(drugImportMaster.getDocumentNo());
            drugStockNew.updateOrgId();

            if(dao.findByBatchNo(drugStockNew).size()>0){
                DrugStock drugStockOld =new DrugStock();
                drugStockOld = dao.findByBatchNo(drugStockNew).get(0);
                allPrice = allPrice + drugStockNew.getQuantity() * drugStockNew.getPurchasePrice();
                //入库的大包装数量*包装数+已有库存量
                DrugInfo drugInfo=drugInfoDao.get(drugStockNew.getInfoId());
                Double newQuantity =0.0;
                if(drugStockNew.getPackageSpec().equals(drugInfo.getPackageSpec())){
                    newQuantity= drugStockNew.getQuantity() * drugInfo.getPackageNum() + drugStockOld.getQuantity();
                }else {
                    newQuantity= drugStockNew.getQuantity() + drugStockOld.getQuantity();
                }
                drugStockOld.setQuantity(newQuantity);
                drugStockOld.setDocumentNo(drugImportMaster.getDocumentNo());
                drugStockOld.setImportMasterId(drugImportMaster.getId());
                drugStockOld.preUpdate();
                num = num * dao.update(drugStockOld);
            }else {
                allPrice = allPrice + drugStockNew.getQuantity() * drugStockNew.getPurchasePrice();
                DrugInfo drugInfo=drugInfoDao.get(drugStockNew.getInfoId());
                Double newQuantity =0.0;
                if(drugStockNew.getPackageSpec().equals(drugInfo.getPackageSpec())){
                    newQuantity= drugStockNew.getQuantity() * drugInfo.getPackageNum();
                }else {
                    newQuantity= drugStockNew.getQuantity();
                }
                drugStockNew.setQuantity(newQuantity);
                drugStockNew.setImportMasterId(drugImportMaster.getId());
                drugStockNew.setSupplierId(drugImportMaster.getSupplier());
                drugStockNew.preInsert();
                num = num * dao.insert(drugStockNew);
            }
        }
        drugImportMaster.setAccountReceivable(allPrice);
        num = num * drugImportMasterDao.update(drugImportMaster);
        return printMasterId;
    }
    /**
     * 过期药品查找
     * @param drugStock
     * @return
     */
    public Page<DrugStock> findDrugStock(Page<DrugStock> page,DrugStock drugStock){
        drugStock.updateOrgId();
        drugStock.setPage(page);
        page.setList(drugStockDao.findDrugStock(drugStock));
        return page;
    }

    /**
     * 盘点的药品列表
     * @param
     * @return
     * @update by CTQ at 2017-07-05 18:52:37
     */
    public Page<DrugStock> findInventoryStockPage(Page<DrugStock> page,DrugInventoryCheck drugInventoryCheck){
        List<DrugStock> list = handleDrugStock(drugInventoryCheck);
        page.setList(list);
        page.setCount(list.size());
        return page;
    }

    /**
     * 查询药品盘点记录
     * @param page
     * @param drugInventoryCheck
     * @return
     * @author CTQ
     * @date 2017-07-05 18:53:17
     */
    public Page<DrugStock> findRecordPage(Page<DrugStock> page,DrugInventoryCheck drugInventoryCheck){
        drugInventoryCheck.setType("2");//已盘点过药品
        List<DrugStock> list = handleDrugStock(drugInventoryCheck);
        page.setList(list);
        page.setCount(list.size());
        return page;
    }

    /**
     * 处理查询条件公用方法
     * @param drugInventoryCheck
     * @return
     * @author CTQ
     * @date 2017-07-05 18:51:32
     */
    private List<DrugStock> handleDrugStock(DrugInventoryCheck drugInventoryCheck){
        DrugStock drugStock=new DrugStock();
        drugStock.setDrugName(null!=drugInventoryCheck.getDrugName()?drugInventoryCheck.getDrugName():"");
        drugStock.updateOrgId();
        drugStock.setStorageId(null!=UserUtils.getUser().getOrgDept()?UserUtils.getUser().getOrgDept().getId():"");
        drugStock.setType(drugInventoryCheck.getType());
       return drugStockDao.findInventoryStock(drugStock);
    }


    /**
     * 药品出库，减库存操作
     * @param drugStock 注意,drugStock表里面的quantity字段是小包装库存数量,不能搞错。传过来定的drugStock参数里quantity也是小包装数量
     * @param exportQuantity  出库数量
     * @return
     * @author fengyg
     */
    @Transactional(readOnly = false)
    public StringData exportStock(DrugStock drugStock,Double exportQuantity){
        StringData data = new StringData();
        List<DrugStock> stocks = dao.findByBatchNo(drugStock);
        if(null != stocks && stocks.size() > 0){
            for (DrugStock stock : stocks) {
                if(stock.getQuantity() < exportQuantity){
                    data.setCode("error");
                    data.setData("该药品当前批次库存数量不够,无法出库!");
                    return data;
                }else{
                    stock.setQuantity(NumberUtils.sub(stock.getQuantity(),exportQuantity));//减库存
                    int num = dao.update(stock);
                    if(num > 0){
                        data.setCode("success");
                        data.setData("药品出库成功!");
                    }else{
                        data.setCode("error");
                        data.setCode("药品出库失败!");
                    }
                    return data;
                }
            }
        }else{
            data.setCode("error");
            data.setData("抱歉,该药品当前批次没有库存!");
            return data;
        }
        return data;
    }

    /**
     * 药品批量入库
     * @param drugImportMaster
     * @return
     * @author fengyg
     */
    @Transactional(readOnly = false)
    public StringData saveBatchImport(DrugImportMaster drugImportMaster) {
        int num = 1;
        StringData data = new StringData();

        DrugExportMaster drugExportMaster = drugExportMasterDao.get(drugImportMaster.getRemarks());
        //根据入库主表id获取要入库的list
        List<DrugExportDetail> drugExportDetailList =new ArrayList<>();
        drugExportDetailList=drugExportDetailDao.findByExportMaster(drugImportMaster.getRemarks());

        DrugStock drugStock = new DrugStock();
        drugStock.setStorageId(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");


        //新建入库主表
        drugImportMaster.setStorageId(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
        drugImportMaster.setImportClass(DictUtils.getDictLabel(drugImportMaster.getImportClass(), "DRUG_STOTARG_TYPE", ""));
        drugImportMaster.setImportDate(new Date());
        drugImportMaster.setStorageFrom(drugExportMaster.getStorageId());
        drugImportMaster.setAccountReceivable(drugExportMaster.getAccountReceivable());
        drugImportMaster.preInsert();
        drugImportMaster.updateOrgId();
        drugImportMaster.setDocumentNo(drugImportMasterService.createDocumentNo(drugImportMaster));
        num=num*drugImportMasterDao.insert(drugImportMaster);

        //修改出库主表信息

        drugExportMaster.setImportDate(new Date());
        drugExportMaster.setImportMasterId(drugImportMaster.getId());
        drugExportMaster.setImportOperator(null != UserUtils.getUser().getId() ? UserUtils.getUser().getId() : "");
        drugExportMaster.preUpdate();
        num=num*drugExportMasterDao.update(drugExportMaster);


        for(int i=0;i<drugExportDetailList.size();i++){
            //组装入库详情表信息保存
            DrugImportDetail drugImportDetail = new DrugImportDetail();
            drugImportDetail.setDocumentNo(drugImportMaster.getDocumentNo());
            drugImportDetail.setMasterId(drugImportMaster.getId());
            drugImportDetail.setDrugCode(drugExportDetailList.get(i).getDrugCode());
            drugImportDetail.setItemNo(i + "");
            drugImportDetail.setInfoId(drugExportDetailList.get(i).getInfoId());
            drugImportDetail.setPackageNum(drugExportDetailList.get(i).getPackageNum());
            drugImportDetail.setPackageSpec(drugExportDetailList.get(i).getPackageSpec());
            drugImportDetail.setPackageUnits(drugExportDetailList.get(i).getPackageUnits());
            drugImportDetail.setMinSpec(drugExportDetailList.get(i).getMinSpec());
            drugImportDetail.setMinUnits(drugExportDetailList.get(i).getMinUnits());
            drugImportDetail.setPurchasePrice(String.valueOf(drugExportDetailList.get(i).getPurchasePrice()));
            drugImportDetail.setBatchNo(drugExportDetailList.get(i).getBatchNo());
            drugImportDetail.setExpireDate(drugExportDetailList.get(i).getExpireDate());
            drugImportDetail.setQuantity(String.valueOf(drugExportDetailList.get(i).getQuantity()));
            drugImportDetail.updateOrgId();
            drugImportDetail.preInsert();
            num=num*drugImportDetailDao.insert(drugImportDetail);

            //存入库存表信息
            DrugStock drugStockImport = new DrugStock();
            drugStockImport=drugStockDao.get(drugExportDetailList.get(i).getDrugStock().getId());
            drugStockImport.setStorageId(null != UserUtils.getUser().getOrgDept() ? UserUtils.getUser().getOrgDept().getId() : "");
            drugStockImport.setQuantity(drugExportDetailList.get(i).getQuantity());
            drugStockImport.setImportMasterId(drugImportMaster.getId());
            drugStockImport.setDocumentNo(drugImportMaster.getDocumentNo());
            //判断库房里面是否有同批次同厂家同规格的该药品，如果有，直接加库存；如果没有，新增一条库存数据
            List<DrugStock> stockOlds = dao.findByBatchNo(drugStockImport);
            if(null != stockOlds && stockOlds.size() > 0){
                DrugStock oldStock = stockOlds.get(0);
                oldStock.setExpireDate(drugStockImport.getExpireDate());
                oldStock.setQuantity(oldStock.getQuantity() + drugStockImport.getQuantity());
                oldStock.setDocumentNo(drugImportMaster.getDocumentNo());
                oldStock.setImportMasterId(drugImportMaster.getId());
                oldStock.preUpdate();
                num += dao.update(oldStock);   //更新库存
            }else{
                drugStockImport.setId("");
                drugStockImport.preInsert();
                num += dao.insert(drugStockImport);     //保存库存
            }

        }



            if (num > 0) {
                data.setCode("success");
                data.setData("药品入库成功!");
            } else {
                data.setCode("error");
                data.setData("药品入库失败!");
            }

        return data;
    }

    /**
     * 根据库房id,infoId获取不同批次的库存大于0的list
     * @return
     * @author zhuq
     */
    public List<DrugStock> findByInfoId (DrugStock drugStock){
//        drugStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
        drugStock.updateOrgId();
        return dao.findByInfoId(drugStock);
    }

    /**
     *根据visitId 获取待退费医嘱药品list
     * @return
     * @author zhuq
     */
    public List<DrugStock> findByVisitId (DrugStock drugStock){
        return dao.findByVisitId(drugStock);
    }

    /**
     *根据visitId 进行医嘱退药
     * @return
     * @author zhuq
     */
    @Transactional(readOnly = false)
    public int inpInStock (DrugStock drugStock){
        int num =1;
        //获取待退药的数量，价格，inpBillDetail的id
        List<DrugStock> drugStockList = dao.findByVisitId(drugStock);
        //退库存并写入inpBillDetail的副记录
        for (int i=0;i<drugStockList.size();i++){
            ApplyDrugWithdra applyDrugWithdra  = applyDrugWithdraDao.get(drugStockList.get(i).getId());
            applyDrugWithdra.setRetType("2");
            applyDrugWithdra.preUpdate();
            applyDrugWithdraDao.update(applyDrugWithdra);

            InpBillDetail inpBillDetail  = inpBillDetailDao.get(drugStockList.get(i).getRemarks());
            inpBillDetail.setAmount(String.valueOf(-1 * drugStockList.get(i).getQuantity()));
            inpBillDetail.setCharges(Double.valueOf(inpBillDetail.getAmount()) * inpBillDetail.getItemPrice());
            inpBillDetail.setCosts(Double.valueOf(inpBillDetail.getAmount()) * inpBillDetail.getItemPrice());
            inpBillDetail.setInpId(inpBillDetail.getId());
            inpBillDetail.setId("");
            inpBillDetail.preInsert();
            inpBillDetailDao.insert(inpBillDetail);

            //根据drugPriceId获取infoId

            DrugPrice drugPrice = drugPriceDao.get(inpBillDetail.getPriceId());
            DrugInfo drugInfo = drugInfoDao.get(drugPrice.getDrugInfo().getId());
            drugStock.setInfoId(drugInfo.getId());
            drugStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
            drugStock.updateOrgId();
            List<DrugStock> listByExpireDate = drugStockDao.findByExpireDate(drugStock);
            Double quantityOut=0.0;
            if(drugPrice.getPackageSpec().equals(drugInfo.getPackageSpec())){
                quantityOut=Double.valueOf(inpBillDetail.getAmount())*drugInfo.getPackageNum();
            }else {
                quantityOut=Double.valueOf(inpBillDetail.getAmount());
            }

            DrugStock drugStock1=listByExpireDate.get(0);
            drugStock1.setQuantity(drugStock1.getQuantity()+ quantityOut );
            drugStock1.preUpdate();
            num=num*drugStockDao.update(drugStock1);
        }
        return num;
    }

}